package com.torry.edss.application.job;

import com.torry.edss.application.cache.TradingDayCache;
import com.torry.edss.infras.util.DateUtil;
import com.torry.edss.integration.facade.RemoteApiFacade;
import com.torry.edss.integration.facade.result.FetchDailyLineResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 刷新交易日信息。
 * 启动时执行一次。 15：40分更新一次。
 *
 * @author torry.wang
 */
@Component
@Slf4j
public class RefreshTradingDayTask implements CommandLineRunner {

    @Resource
    private RemoteApiFacade remoteApiFacade;

    final String SZ_CODE = "000001";
    final String SH_CODE = "600000";
    final int MAX_SIZE = 99999;
    final String END_TIME = "16:30:00";

    @Override
    public void run(String... args) {
        List<FetchDailyLineResult> list = remoteApiFacade.fetchAllDailyLines(SH_CODE);
        List<String> shTradingDays = list.stream().map(FetchDailyLineResult::getDate).collect(Collectors.toList());

        list = remoteApiFacade.fetchAllDailyLines(SZ_CODE);
        List<String> szTradingDays = list.stream().map(FetchDailyLineResult::getDate).collect(Collectors.toList());
        List<String> allTradingDays = Stream.concat(shTradingDays.stream(), szTradingDays.stream())
                .distinct().sorted(String::compareTo).collect(Collectors.toList());

        LocalDateTime now = LocalDateTime.now();
        if (allTradingDays.get(allTradingDays.size() - 1).equals(DateUtil.formatDate(now))) {
            String s = DateUtil.formatDate(now) + " " + END_TIME;
            // 如果此时在16：30之前,将最后一个交易日改为上一天
            if (now.isBefore(DateUtil.parseDateTime(s))) {
                allTradingDays.remove(DateUtil.formatDate(now));
            }
        }
        TradingDayCache.setLastTradingDay(allTradingDays.get(allTradingDays.size() - 1));
        TradingDayCache.setAllTradingDays(allTradingDays);

        log.info("======== init or update lastTradingDay: {} ========", TradingDayCache.getLastTradingDay());
        log.info("======== init or update allTradingDays. size: {} ========", TradingDayCache.getAllTradingDays().size());
    }

    @Scheduled(cron = "0 30 16 * * ?")
    public void refreshTradingDayCache() {
        run();
    }
}